<template>
  <div class="app-container">
    <el-card>
      <div class="main-title">字典管理</div>
      <!--查询区域-->
      <div class="search-card">
        <div class="search-form" size="mini">
          <el-form ref="queryParamFrom" :model="queryParam">
            <div class="search-form-item">
              <el-button type="primary" icon="el-icon-plus" size="medium" @click="AddOrModifyDictClick('add', -1)">新增</el-button>
            </div>
            <!--<div class="search-form-item">
              &lt;!&ndash; <el-button type="primary" icon="el-icon-folder-add" size="medium" @click="AddOrModifyDictClick('add', -1)">新增</el-button> &ndash;&gt;
              <el-button type="primary" size="medium" @click="AddOrModifyDictClick('add', -1)">
                <i class="iconfont Icon_add_dictionary vereCenter" style="margin-right: 5px;vertical-align: middle;" />新增
              </el-button>
            </div>-->
            <el-divider class="mr-20" direction="vertical"/>
            <div class="search-form-item">
              <i class="el-icon-search"/>
              <span>查询：</span>
            </div>
            <div class="search-form-item">
              <el-input v-model="queryParam.code" placeholder="请填写字典类型编码"/>
            </div>
            <div class="search-form-item">
              <el-input v-model="queryParam.name" placeholder="请填写字典类型名称"/>
            </div>
            <div class="search-form-item">
              <el-select v-model="queryParam.isEnable" size="medium" placeholder="状态">
                <el-option label="启用" value="0"/>
                <el-option label="停用" value="1"/>
              </el-select>
            </div>
            <div class="search-form-item">
              <el-button type="primary" @click="onSubmit">查询</el-button>
              <el-button @click="resetForm('queryParamFrom')">清空</el-button>
            </div>
          </el-form>
        </div>
      </div>

      <!--表格区域-->
      <el-table v-loading="listLoading" :data="tableData" :header-cell-style="headerCellStyle" class="table-area" stripe>
        <el-table-column prop="name" label="字典类型编码">
          <template slot-scope="scope">
            <span style="color:#2281f5">{{ scope.row.code || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="requestType" label="字典类型名称">
          <template slot-scope="scope">
            <span style="color:#2281f5">{{ scope.row.name || '--' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="functionName" label="状态" width="86px">
          <template slot-scope="scope">
            <!-- <span v-if="scope.row.isEnable === 0">启用</span>
            <span v-else>停用</span> -->
            <div v-if="scope.row.isEnable === 0" class="mydefineDiv">
              <img src="../../../assets/status_normal.png" style="vertical-align: middle">
              <span style="color:#1eb955;vertical-align: middle">启用</span>
            </div>
            <div v-else class="mydefineDiv">
              <img src="../../../assets/status_stop.png" style="vertical-align: middle">
              <span style="color:#f8524f;vertical-align: middle">停用</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="logTemplete" label="创建时间">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="logTemplete" label="更新时间">
          <template slot-scope="scope">
            <span>{{ scope.row.updateTime || '--' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="logTemplete" label="操作" width="320px">
          <template slot-scope="scope">
            <!-- <el-button type="text" size="small" icon="el-icon-edit-outline" @click="AddOrModifyDictClick('update', scope.row)">修改</el-button>
            <el-button type="text" size="small" icon="el-icon-document" @click="checkDictClick(scope.row)">查看</el-button>
            <el-button type="text" size="small" icon="el-icon-turn-off" @click="stopDictStatusClick(scope.row)" v-if="scope.row.isEnable === 0">停用</el-button>
            <el-button type="text" size="small" icon="el-icon-open" @click="stopDictStatusClick(scope.row)" v-else>启用</el-button>
            <el-button type="text" size="small" icon="el-icon-close" @click="deleDictStatusClick(scope.row)">删除</el-button>  -->

            <!-- <button class="myDefineButton" @click="AddOrModifyDictClick('update', scope.row)"><img src="../../../assets/img/edit.png"><span>修改</span></button>
            <button class="myDefineButton" @click="checkDictClick(scope.row)"><img src="../../../assets/img/view.png"><span>查看</span></button>
            <button class="myDefineButton" @click="stopDictStatusClick(scope.row)" v-if="scope.row.isEnable === 0"><img src="../../../assets/img/inactivate.png"><span>停用</span></button>
            <button class="myDefineButton" @click="stopDictStatusClick(scope.row)" v-else><img src="../../../assets/img/activate.png"><span>启用</span></button>
            <button class="myDefineButton" @click="deleDictStatusClick(scope.row)"><img src="../../../assets/img/delete.png"><span>删除</span></button> -->

            <el-button type="text" size="middle" class="vereImg" @click="AddOrModifyDictClick('update', scope.row)">
              <i class="iconfont Icon_edit vereCenter" style="margin-right: 5px;vertical-align: middle;" />修改
            </el-button>

            <el-button type="text" size="middle" class="vereImg" @click="checkDictClick(scope.row)">
              <i class="iconfont Icon_view vereCenter" style="margin-right: 5px;vertical-align: middle;"/>查看
            </el-button>
            <!-- 启/停用 -->
            <el-button v-if="scope.row.isEnable === 0" type="text" size="middle" class="vereImg" @click="stopDictStatusClick(scope.row)">
              <i class="iconfont Icon_inactive vereCenter" style="margin-right: 5px;vertical-align: middle;" />停用
            </el-button>
            <el-button v-else type="text" size="middle" class="vereImg" @click="stopDictStatusClick(scope.row)">
              <i class="iconfont Icon_active vereCenter" style="margin-right: 5px;vertical-align: middle;" />启用
            </el-button>
            <el-button type="text" size="middle" class="vereImg verImgdelete" @click="deleDictStatusClick(scope.row)">
              <i class="iconfont Icon_delete vereCenter" style="margin-right: 5px;vertical-align: middle;" />删除
            </el-button>
          </template>
        </el-table-column>

      </el-table>
      <div v-if="total > 0" class="page-main">
        <el-pagination :current-page="queryParam.pageNo" :total="total" background layout="total, prev, pager, next" @current-change="handleCurrentChange"/>
      </div>
    </el-card>
    <!--对话框表单-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="40%" class="dialog-box" @close="resetDialogForm" @closed="handleDialogClosed">
      <el-form ref="dialogForm" :model="dialogForm" :rules="dialogFormRules" label-width="106px">
        <el-form-item label="字典类型编码" prop="code">
          <el-input v-model="dialogForm.code" :size="dialogFormItemSize" maxlength="100" placeholder="请填写字典类型编码"/>
        </el-form-item>
        <el-form-item label="字典类型名称" prop="name">
          <el-input v-model="dialogForm.name" type="text" placeholder="请填写字典类型名称" maxlength="100" show-word-limit/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button :loading="submitLoading" size="small" type="primary" @click="submitDialog">提交</el-button>
        <el-button size="small" @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import { formatTime, dealObjectValue } from '@/utils/common'
import { getDictionaryTypeList, AddOrUpdateDictionaryType, changeDictionaryTypeStatus } from '@/api/sysSettings/dictManage'
export default {
  name: 'DictManage',
  data() {
    return {
      // 查询参数
      queryParam: {
        'code': '',
        'name': '',
        'isEnable': '',
        'pageNo': 1, // 当前页
        'pageSize': 10 // 每页条数
      },
      listLoading: false, // 列表区域加载中
      tableData: [], // 表格数据
      detailData: {}, // 详情信息
      total: 0, // 列表总条数
      headerCellStyle() { return 'background-color: #f5f8fd;color: #000' }, // 表格表头样式

      dialogVisible: false, // 对话框显示/隐藏
      dialogTitle: '', // 对话框标题
      dialogType: '', // 对话框类型（添加 or 修改）
      dialogFormItemSize: 'medium', // 表单填写框尺寸
      dialogSiteSelectData: [], // 对话框站点选择框数据
      dialogCarSelectData: [], // 对话框车辆列表
      // 对话框表单
      dialogForm: {
        code: '',
        name: ''
      },
      // 表单验证规则
      dialogFormRules: {
        code: [{ required: true, trigger: 'blur', validator: (rule, value, callback) => {
          if (value.length > 100 || value.length < 1) {
            callback(new Error('长度必须为1~100个字符'))
          } else {
            var reg = new RegExp("[`~!@#$^&*()=|{}':',\\[\\].<>《》/?~！@#￥……&*（）——|{}【】‘；：”“'。，、？]")
            var EngDigitReg = new RegExp('[\u4e00-\u9fa5]') // 由数字、26个英文字母或者下划线组成的字符串
            if (reg.test(value)) {
              callback(new Error('编码不能包含特殊字符！'))
            } else if (EngDigitReg.test(value)) {
              callback(new Error('编码不能包含中文字符！'))
            } else {
              callback()
            }
          }
        } }],
        name: [{ required: true, message: '请填写字典类型名称', trigger: 'blur' }]
      },
      submitLoading: false // 对话框表单提交按钮加载中
    }
  },
  created() {
    this.getDictionaryList()
  },
  methods: {
    // 查询
    onSubmit() {
      this.queryParam.pageNo = 1
      this.getDictionaryList()
    },

    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
      this.queryParam = {
        code: '',
        name: '',
        isEnable: ''
      }
      this.queryParam.pageNo = 1
      this.getDictionaryList()
    },

    // 改变当前页
    handleCurrentChange(val) {
      this.queryParam.pageNo = val
      this.getDictionaryList()
    },

    // 获取字典类型列表
    getDictionaryList() {
      this.listLoading = true

      const param = dealObjectValue(this.queryParam)
      // console.log(param)
      getDictionaryTypeList(param).then(response => {
        this.listLoading = false
        const data = response.object
        const list = data.list || []
        this.total = response.object.total
        if (list.length > 0) {
          list.forEach(item => {
            if (item.createTime) {
              item.createTime = this.getFormatTime(item.createTime)
            }
            if (item.updateTime) {
              item.updateTime = this.getFormatTime(item.updateTime)
            }
          })
        } else {
          this.$message.warning('暂无数据')
        }
        this.tableData = list
      }).catch(() => {
        this.listLoading = false
      })
    },

    // 重置对话框表单
    resetDialogForm() {
      this.$refs['dialogForm'].resetFields()
      this.officeValue = ''
      this.dialogForm = {
        code: '',
        name: ''
      }
    },
    handleDialogClosed() {
      this.submitLoading = false
      this.$refs['dialogForm'].clearValidate() // 清除验证信息
    },
    // 添加或修改
    AddOrModifyDictClick(type, val) {
      this.dialogType = type
      if (type === 'add') {
        this.dialogTitle = '添加字典类型'
      } else if (type === 'update') {
        // console.log(val)
        this.dialogTitle = '修改字典类型'
        this.dialogForm = {
          code: val.code,
          name: val.name,
          id: val.id
        }
      }
      this.dialogVisible = true
    },
    // 提交对话框表单
    submitDialog() {
      this.$refs['dialogForm'].validate((valid) => {
        if (valid) {
          const param = this.dialogForm
          this.submitLoading = true
          AddOrUpdateDictionaryType(param).then(response => {
            this.dialogVisible = false
            this.getDictionaryList()
          }).catch(() => {
            this.submitLoading = false
          })
        }
      })
    },
    // 查看
    checkDictClick(val) {
      this.$router.push('/system/dictionaries/dictionaryData/' + val.id + '/' + val.code)
    },

    // 停用
    stopDictStatusClick(val) {
      const param = {
        id: val.id,
        isEnable: (val.isEnable === 0) ? 1 : 0
      }
      this.submitLoading = true
      changeDictionaryTypeStatus(param).then(response => {
        this.dialogVisible = false
        this.getDictionaryList()
      }).catch(() => {
        this.submitLoading = false
      })
    },

    // 删除
    deleDictStatusClick(val) {
      const param = {
        id: val.id,
        isDelete: (val.isDelete === 0) ? 1 : 0
      }
      this.submitLoading = true
      changeDictionaryTypeStatus(param).then(response => {
        this.dialogVisible = false
        this.getDictionaryList()
      }).catch(() => {
        this.submitLoading = false
      })
    },

    /* 格式化时间 */
    getFormatTime(time) {
      return formatTime(time, true)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import '../../../styles/settings.scss';
  .btn-group {
    padding: 16px 20px;
  }
  .table-area {
    padding: 0 20px;
  }
  .product-status {
    width: 58px;
    height: 28px;
    line-height: 28px;
    display: inline-block;
    text-align: center;
    border-radius: 4px;
    background: #f2fff7;
    border: 1px solid #1eb955;
    color: #1eb955;
  }
  .product-status.active {
    background: #f3f3f3;
    border: 1px solid #999;
    color: #999;
  }

  // 查询区域
  .search-card {
    padding: 16px 22px;
    display: flex;
    align-items: center;
    background-color: #FFF;
    .query-text {
      width: 80px;
    }
    .search-form {
      .search-form-item {
        display: inline-block;
        margin-right: 10px;
        margin-bottom: 6px;
      }
    }
  }

  .item-box {
    display: flex;
    justify-content: space-between;
    line-height: 30px;
    .detail-item {
      width: 50%;
    }
  }
  .tree-box {
    border: 1px solid #ebeef5;
    .tree-title {
      background-color: #f5f7fa;
      padding: 10px;
    }
  }
</style>
